package com.android.questions.ui.fragment;

import android.Manifest;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.viewbinding.ViewBinding;

import com.android.base.ui.base.VBBaseFragment;
import com.android.base.util.ActivityClickUtil;
import com.android.base.util.DQLog;
import com.android.base.util.NumberFormatUtil;
import com.android.base.util.SystemUtil;
import com.android.base.util.ToastUtil;
import com.android.questions.R;
import com.android.questions.config.AppConfig;
import com.android.questions.config.LoginConfig;
import com.android.questions.databinding.FragmentMeBinding;
import com.android.questions.ui.activity.LoginActivity;
import com.android.questions.ui.activity.MainActivity;
import com.android.questions.ui.activity.SettingActivity;
import com.android.questions.ui.activity.WithdrawalRecordActivity;
import com.android.questions.ui.adapter.BalanceAdapter;
import com.android.questions.ui.dialog.DialogAddCoin;
import com.android.questions.ui.dialog.DialogAddCoinResult;
import com.android.questions.ui.dialog.DialogJointQQ;
import com.android.questions.ui.dialog.DialogWithError;
import com.android.questions.ui.dialog.DialogWithdrawalSuccess;
import com.android.questions.util.AnimUtil;
import com.android.questions.util.Command;
import com.android.questions.util.sound.MediaBackManager;
import com.dq.ad.AdManager;
import com.dq.ad.UMManager;
import com.hx.currency.HXCurrencySDK;
import com.hx.currency.data.qa.api.QAWatchVideoResp;
import com.hx.currency.data.qa.api.QAWithdrawConfigResp;
import com.hx.currency.data.qa.api.QAWithdrawResp;
import com.hx.currency.data.qa.model.QAWithdraw;
import com.qq.e.o.ads.v2.error.AdError;
import com.qq.e.o.data.HttpUtil;
import com.qq.e.o.utils.ILog;
import com.qq.e.o.utils.JsonUtil;

import java.util.List;
import java.util.Locale;
import java.util.Random;

/**
 * FileName: MeFragment
 * Author: admin
 * Date: 2021/11/2 9:26
 * Description:
 */
public class MeFragment extends VBBaseFragment implements View.OnClickListener, BalanceAdapter.OnItemSelectLister, MainActivity.OnTouchEvent {

    private FragmentMeBinding meBinding;
    private BalanceAdapter balanceAdapter;
    private int selectPos = 0;

    private MainActivity mainActivity;
    private boolean isReward = true;

    private final ActivityResultLauncher<String> requestPermission = registerForActivityResult(new ActivityResultContracts.RequestPermission(), new ActivityResultCallback<Boolean>() {
        @Override
        public void onActivityResult(Boolean result) {
            withdrawal();
        }
    });

    public static MeFragment createFragment() {
        return new MeFragment();
    }

    @Override
    protected ViewBinding getViewBinding(LayoutInflater inflater) {
        setTitleBackground(BG_WHITE);
        return meBinding = FragmentMeBinding.inflate(inflater);
    }

    @Override
    public void initView() {
        super.initView();
        mainActivity = (MainActivity) activity;
        meBinding.tvTitle.setText("我的钱包");
        String tips = "您可以通过<font color='#FD0D21'>答题</font>或领取各类<font color='#FD0D21'>活动红包</font>来完成视频提现任务哦";
        meBinding.tvWithdrawalDesc.setText(Html.fromHtml(tips));
        balanceAdapter = new BalanceAdapter();

        String rule = "1.微信提现需要实名制，非实名用户账户无法支持提现。\n" +
                "2.提现申请通常1-3个工作日内审核到账，请耐心等待。\n" +
                "3.系统判定日常活跃度不达标者，红包余额会对应减少。\n" +
                "4.如发现作弊、外挂等违规手段获取奖励，官方有权判定奖励无效且对违规账号进行封禁。";
        meBinding.tvWithdrawRule.setText(rule);

        AnimUtil.receiveAnim(activity, meBinding.ivRedPacket);

        if (LoginConfig.getAddCoinTimes() >= AppConfig.COIN_TIMES_MAX) {
            meBinding.ivAddCoin.setImageResource(R.drawable.ic_watch_video_btn_gray);
        }
    }

    @Override
    public void initData() {
        super.initData();
        getBalanceData();
    }

    @Override
    public void initLister() {
        super.initLister();
        meBinding.imgBack.setOnClickListener(this);
        meBinding.imgSetting.setOnClickListener(this);
        meBinding.ivAddCoin.setOnClickListener(this);
        meBinding.imgWithdrawal.setOnClickListener(this);
        meBinding.lcQqTips.setOnClickListener(this);
        meBinding.tvWithdrawalRecord.setOnClickListener(this);
        balanceAdapter.setItemSelectLister(this);
        mainActivity.setOnTouchEvent(this);
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        updateCoinInfo();
    }

    private void updateCoinInfo() {
        String cashStr = String.format(Locale.getDefault(), "%d=%s元", (int) LoginConfig.getUserCash(), NumberFormatUtil.convertDoubleToString(LoginConfig.getUserCash() * LoginConfig.getCashConvert()));
        meBinding.tvCash.setText(cashStr);
    }

    public void getBalanceData() {
        HXCurrencySDK.getInstance().getQAWithdrawConfig(1, new HttpUtil.HttpUtilCallback() {
            @Override
            public void onSuccess(int i, String response) {
                DQLog.e("提现列表获取成功：" + response);
                if (activity.isFinishing()) {
                    return;
                }
                QAWithdrawConfigResp qaWithdrawConfigResp = JsonUtil.parseObject(response, QAWithdrawConfigResp.class);
                if (qaWithdrawConfigResp != null) {
                    if (qaWithdrawConfigResp.getErrorCode() == 0) {
                        updateUI(qaWithdrawConfigResp.getWavl());
                    } else {
                        DQLog.e("获取提现列表异常：" + qaWithdrawConfigResp.getErrorMessage());
                    }
                } else {
                    DQLog.e("获取提现列表异常");
                    ToastUtil.showShortToast(activity, "数据未配置");
                }
            }

            @Override
            public void onFailed(int i, Throwable throwable) {
                DQLog.e("获取提现列表异常：" + throwable.toString());
            }
        });
    }

    /**
     * 提现
     */
    private void withdrawal() {
        if (selectPos == -1) {
            ToastUtil.showShortToast(activity, "请先选择提现金额");
            return;
        }
        if (AppConfig.tiXianPos != -1 && AppConfig.tiXianPos != selectPos) {
            new DialogWithError(activity).setType(DialogWithError.TYPE_TIPS).setTipStr("请先完成上一条提现").show();
            return;
        }
        if (AppConfig.getRemainWithdrawalTimes() <= 0) {
            ToastUtil.showShortToast(activity, "明日可继续提现");
            return;
        }
        List<QAWithdraw> qaWithdrawList = balanceAdapter.getData();
        if (qaWithdrawList.size() <= 0) {
            ToastUtil.showShortToast(activity, "提现配置获取失败，请退出应用后重试");
            return;
        }
        QAWithdraw qaWithdraw = qaWithdrawList.get(selectPos);
        int wc = qaWithdraw.getWc();

        if (selectPos == 0) {
            if (wc <= 0) {
                ToastUtil.showShortToastCenter(activity, "提现次数已用完");
                return;
            }
            UMManager.onEvent(UMManager.Event.Withdrawal_click_1);
        } else if (selectPos == 1) {
            if (wc <= 0) {
                ToastUtil.showShortToastCenter(activity, "提现次数已用完");
                return;
            }
            UMManager.onEvent(UMManager.Event.Withdrawal_click_2);
        } else if (selectPos == 2) {
            if (wc <= 0) {
                ToastUtil.showShortToastCenter(activity, "提现次数已用完");
                return;
            }
            UMManager.onEvent(UMManager.Event.Withdrawal_click_3);
        } else if (selectPos == 3) {
            if (wc <= 0) {
                ToastUtil.showShortToastCenter(activity, "提现次数已用完");
                return;
            }
            UMManager.onEvent(UMManager.Event.Withdrawal_click_4);
        } else if (selectPos == 4) {
            if (wc <= 0) {
                ToastUtil.showShortToastCenter(activity, "提现次数已用完");
                return;
            }
            UMManager.onEvent(UMManager.Event.Withdrawal_click_5);
        } else if (selectPos == 5) {
            if (wc <= 0) {
                ToastUtil.showShortToastCenter(activity, "提现次数已用完");
                return;
            }
            UMManager.onEvent(UMManager.Event.Withdrawal_click_6);
        } else if (selectPos == 6) {
            UMManager.onEvent(UMManager.Event.Withdrawal_click_7);
        } else if (selectPos == 7) {
            UMManager.onEvent(UMManager.Event.Withdrawal_click_8);
        } else if (selectPos == 8) {
            UMManager.onEvent(UMManager.Event.Withdrawal_click_9);
        }

        if (qaWithdraw.getWa() > LoginConfig.getUserCash() * LoginConfig.getCashConvert()) {
            UMManager.onEvent(UMManager.Event.Withdrawal_click_Insufficient);
            if (LoginConfig.getAddCoinTimes() >= AppConfig.COIN_TIMES_MAX) {
                ToastUtil.showShortToast(activity, "余额不足");
            } else {
                // 弹窗 看视频补充红包券
                new DialogAddCoin(activity).setOnClickLister(new DialogAddCoin.OnClickLister() {
                    @Override
                    public void onWatchVideo() {
                        UMManager.onEvent(UMManager.Event.Supplement_Hongbao2);
                        watchVideo();
                    }
                }).show();
            }

            return;
        }

        if (TextUtils.isEmpty(LoginConfig.getUserOpenId())) {
            LoginActivity.startAct(activity, LoginActivity.TYPE_BIND, null);
            selectPos = 0;
            updateCoinInfo();
            balanceAdapter.notifyDataSetChanged();
            return;
        }

        if (qaWithdraw.getWv() > 0) {//如果剩余需要看广告次数>0
            if (AppConfig.tiXianPos == -1) {//如果服务器没有创建提现剩余观看视频数任务，就创建任务
                requestWithdrawal(qaWithdraw.getWid(), qaWithdraw.getWlt(), qaWithdraw.getWa());
            } else {//如果服务器已经创建提现剩余观看视频数任务，就直接弹出去完成框
                new DialogWithError(activity).setType(DialogWithError.TYPE_NUM).setNum(qaWithdraw.getWv()).show();
            }
            return;
        }

        if (AppConfig.hasQQStatus == 1 && AppConfig.hasQQ == 0) {
            new DialogJointQQ(activity).show();
        } else if (AppConfig.localPermission == 0 || AppConfig.getRequestPosPermission()) {
            requestAd(qaWithdraw);
        } else {
            AppConfig.setRequestPosPermission(true);

            requestPermission.launch(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
    }

    private void requestAd(QAWithdraw qaWithdraw) {
        if (AppConfig.hasNoAd()) {
            requestWithdrawal(qaWithdraw.getWid(), qaWithdraw.getWlt(), qaWithdraw.getWa());
        } else {
            meBinding.imgWithdrawal.setEnabled(false);
            isReward = false;
            if (AppConfig.getBackMusic()) {
                MediaBackManager.getInstance(activity).pause();
            }
            AdManager.getInstance().showRewardVideoAD("", activity, new AdManager.OnRewardVideoADListener() {
                @Override
                public void onClosed(String orderId) {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    meBinding.imgWithdrawal.setEnabled(true);
                    if (isReward) {
                        requestWithdrawal(qaWithdraw.getWid(), qaWithdraw.getWlt(), qaWithdraw.getWa());
                    } else {
                        ToastUtil.showShortToast(activity, "未完整观看视频，提现失败");
                    }
                }

                @Override
                public void onReward() {
                    isReward = true;
                }

                @Override
                public void onShow(double ecpm) {
                }

                @Override
                public void onFailed(int i, AdError adError) {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    ILog.e("MeFragment onFailed: " + adError.getErrorMsg());
                    meBinding.imgWithdrawal.setEnabled(true);
                    requestWithdrawal(qaWithdraw.getWid(), qaWithdraw.getWlt(), qaWithdraw.getWa());
                }

                @Override
                public void onTimeout() {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    ILog.e("MeFragment onTimeout");
                    meBinding.imgWithdrawal.setEnabled(true);
                    requestWithdrawal(qaWithdraw.getWid(), qaWithdraw.getWlt(), qaWithdraw.getWa());
                }
            });
        }
    }

    private void requestWithdrawal(int amid, int typeWithdrawal, double withdrawAmount) {
        HXCurrencySDK.getInstance().qaWithdraw(amid, typeWithdrawal, withdrawAmount, 1, new HttpUtil.HttpUtilCallback() {
            @Override
            public void onSuccess(int i, String response) {
                DQLog.e("提现结果：" + response);
                if (activity.isFinishing()) {
                    return;
                }
                QAWithdrawResp qaWithdrawResp = JsonUtil.parseObject(response, QAWithdrawResp.class);
                if (qaWithdrawResp != null) {
                    updateUI2(qaWithdrawResp);
                } else {
                    DQLog.e("提现异常");
                }
            }

            @Override
            public void onFailed(int i, Throwable throwable) {
                DQLog.e("提现异常：" + throwable.toString());
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (ActivityClickUtil.getInstance().isFastClick()) {
            //防止用户快速点击
            return;
        }
        if (v.getId() == R.id.imgWithdrawal) {
            withdrawal();
        } else if (v.getId() == R.id.tvWithdrawalRecord) {
            WithdrawalRecordActivity.startActivity(activity);
        } else if (v.getId() == R.id.imgSetting) {
            SettingActivity.startActivity(activity);
        } else if (v.getId() == R.id.iv_add_coin) {
            UMManager.onEvent(UMManager.Event.Supplement_Hongbao1);
            watchVideo();
        } else if (v.getId() == R.id.lc_qq_tips) {
            SystemUtil.joinQQGroup(activity, AppConfig.QQ_GROUP_KEY);
        } else if (v.getId() == R.id.imgBack) {
            onBackPressedSupport();
        }
    }

    @Override
    public void onSelect(int position) {
        this.selectPos = position;
    }

    private void updateUI(List<QAWithdraw> qaWithdrawList) {
        AppConfig.tiXianPos = -1;
        meBinding.recyclerView.setLayoutManager(Command.Method.getGridLayoutManager(activity, 3, false));
        meBinding.recyclerView.setAdapter(balanceAdapter);
        balanceAdapter.setList(qaWithdrawList);
    }

    public void updateUI2(QAWithdrawResp qaWithdrawResp) {
        if (activity.isFinishing()) {
            return;
        }
        int errorCode = qaWithdrawResp.getErrorCode();
        String errorMessage = qaWithdrawResp.getErrorMessage();
        QAWithdraw qaWithdraw = balanceAdapter.getData().get(selectPos);
        if (errorCode == 10025) {
            new DialogWithError(activity).setType(DialogWithError.TYPE_QUEUE).show();
        } else if (errorCode == 10026) {
            withdrawalSuccess(true, qaWithdrawResp);
        } else if (errorCode == 10028) {
            new DialogWithError(activity).show();
        } else if (errorCode == 10029) {
            new DialogWithError(activity).setType(DialogWithError.TYPE_TIME).setNum(Integer.parseInt(errorMessage)).show();
        } else if (errorCode == 10030) {
            int num = Integer.parseInt(errorMessage);
            qaWithdraw.setVt(1);
            if (balanceAdapter != null) {
                qaWithdraw.setWv(num);
                balanceAdapter.notifyDataSetChanged();
            }
            if (num > 0) {
                new DialogWithError(activity).setType(DialogWithError.TYPE_NUM).setNum(num).show();
            }
        } else if (errorCode == 0) {
//            balanceAdapter.getData().get(selectPos).vt = 0;
//            AppConfig.tiXianPos = -1;
//            if (balanceAdapter.getData().get(selectPos).wc > 0){
//                balanceAdapter.getData().get(selectPos).wc--;
//            }
            if (selectPos == 0) {
                UMManager.onEvent(UMManager.Event.Withdrawal_success_1);
            } else if (selectPos == 1) {
                UMManager.onEvent(UMManager.Event.Withdrawal_success_2);
            } else if (selectPos == 2) {
                UMManager.onEvent(UMManager.Event.Withdrawal_success_3);
            } else if (selectPos == 3) {
                UMManager.onEvent(UMManager.Event.Withdrawal_success_4);
            } else if (selectPos == 4) {
                UMManager.onEvent(UMManager.Event.Withdrawal_success_5);
            } else if (selectPos == 5) {
                UMManager.onEvent(UMManager.Event.Withdrawal_success_6);
            }

            withdrawalSuccess(false, qaWithdrawResp);
        } else {
            ToastUtil.showShortToastCenter(activity, errorMessage);
        }
    }

    private void withdrawalSuccess(boolean isQueue, QAWithdrawResp qaWithdrawResp) {
        selectPos = 0;
        LoginConfig.setUserCash(qaWithdrawResp.getRat() / LoginConfig.getCashConvert());
        int remainWithdrawalTimes = AppConfig.getRemainWithdrawalTimes();
        if (remainWithdrawalTimes >= 1) {
            AppConfig.setRemainWithdrawalTimes(remainWithdrawalTimes - 1);
        }
        new DialogWithdrawalSuccess(activity).setCash(qaWithdrawResp.getWlat()).setQueue(isQueue).setClickLister(new DialogWithdrawalSuccess.OnClickLister() {
            @Override
            public void onWithdrawal() {
                // 继续赚钱
                AppConfig.isGoonMakeMoney = true;
                mainActivity.showHome();
            }
        }).show();
        updateCoinInfo();
        getBalanceData();
    }

    private void watchVideo() {
        if (LoginConfig.getAddCoinTimes() >= AppConfig.COIN_TIMES_MAX) {
            ToastUtil.showShortToast(activity, "今日次数已领完");
            return;
        }

        isReward = false;
        if (AppConfig.hasNoAd()) {
            AppConfig.showNoAdToast(activity);
        } else {
            if (AppConfig.getBackMusic()) {
                MediaBackManager.getInstance(activity).pause();
            }
            AdManager.getInstance().showRewardVideoAD("", activity, new AdManager.OnRewardVideoADListener() {
                @Override
                public void onClosed(String orderId) {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    if (isReward) {
                        addCoin(orderId);
                        getBalanceData();
                    } else {
                        ToastUtil.showShortToast(activity, "未完整观看视频，领取失败");
                    }
                }

                @Override
                public void onReward() {
                    isReward = true;
                }

                @Override
                public void onShow(double ecpm) {
                }

                @Override
                public void onFailed(int i, AdError adError) {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                }

                @Override
                public void onTimeout() {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                }
            });
        }
    }

    private void addCoin(String orderId) {
        int coin = new Random().nextInt(40) + 200;
        HXCurrencySDK.getInstance().qaWatchVideo(2, coin, orderId, new HttpUtil.HttpUtilCallback() {
            @Override
            public void onSuccess(int i, String response) {
                DQLog.e("提现页面 看视频补充红包券成功：" + response);
                if (activity.isFinishing()) {
                    return;
                }
                QAWatchVideoResp qaWatchVideoResp = JsonUtil.parseObject(response, QAWatchVideoResp.class);
                if (qaWatchVideoResp != null) {
                    if (qaWatchVideoResp.getErrorCode() == 0) {
                        LoginConfig.setAddCoinTimes(LoginConfig.getAddCoinTimes() + 1);

                        if (LoginConfig.getAddCoinTimes() >= AppConfig.COIN_TIMES_MAX) {
                            meBinding.ivAddCoin.setImageResource(R.drawable.ic_watch_video_btn_gray);
                        }

                        double ra = qaWatchVideoResp.getRa();
                        LoginConfig.setUserCash(LoginConfig.getUserCash() + ra);
                        updateCoinInfo();
                        new DialogAddCoinResult(activity).setMoney(ra).show();
                    } else {
                        String errorMessage = qaWatchVideoResp.getErrorMessage();
                        if (errorMessage.isEmpty()) {
                            errorMessage = "错误码=" + qaWatchVideoResp.getErrorCode();
                        }
                        ToastUtil.showShortToast(activity, "提现页面 看视频补充红包券失败：" + errorMessage);
                    }
                } else {
                    ToastUtil.showShortToast(activity, "提现页面 看视频补充红包券失败");
                }
            }

            @Override
            public void onFailed(int i, Throwable throwable) {
                DQLog.e("提现页面 看视频补充红包券失败：" + throwable.getMessage());
                ToastUtil.showShortToast(activity, "提现页面 看视频补充红包券失败：" + throwable.getMessage());
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void touchEvent(MotionEvent event) {
        if (AppConfig.getMeBalanceState()) {
            if (balanceAdapter != null) {
                AppConfig.setMeBalanceState(false);
                balanceAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        AppConfig.isGoonMakeMoney = false;
        mainActivity.showHome();
        return true;
    }
}